package cn.mxz.service.impl;

import cn.mxz.mapper.OrderItemMapper;
import cn.mxz.mapper.OrdersMapper;
import cn.mxz.mapper.ProductSkuMapper;
import cn.mxz.pojo.OrderItem;
import cn.mxz.pojo.Orders;
import cn.mxz.pojo.ResultData;
import cn.mxz.pojo.ShoppingCart;
import cn.mxz.service.OrderService;
import cn.mxz.utils.OrderItemIdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author 小毛
 * @Date 2021/12/4 11:00
 * @Remark 佛祖保佑永无bug~
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ProductSkuMapper skuMapper;

    @Override
    public ResultData selectByUserId(String userId) {
        List<Orders> ordersList = ordersMapper.selectAllOrdersByUserId(userId);
        if (ordersList.size() > 0) return new ResultData(0,"查询成功",ordersList);
        return new ResultData(306,"查询订单的接口异常");
    }

    @Override
    public ResultData selectByStatus(String userId, String status) {
        List<Orders> ordersList = ordersMapper.selectAllOrdersByStatus(userId, status);
        if (ordersList.size() > 0 || CollectionUtils.isEmpty(ordersList)) return new ResultData(0,"查询成功",ordersList);
        return new ResultData(308,"根据状态查询的接口异常");
    }

    @Override
    public ResultData deleteByOrderId(String orderId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("order_id",orderId);
        int delete = ordersMapper.delete(qw);
        int delete1 = orderItemMapper.delete(qw);
        if (delete > 0 && delete1 >0) return new ResultData(0,"删除成功！");
        return new ResultData(309,"根据订单ID删除的接口异常");
    }

    @Override
    public ResultData insertOrder(List<ShoppingCart> cartlist, String name, String mobile, String province,
                                  String city, String area, String addr,String userId) {
        try {
            //随机生成订单ID
            String orderId = UUID.randomUUID().toString().replace("-", "");
            //生成添加订单的时间
            Date currentTime = new Date();
            //订单的名字
            StringBuilder untitled = new StringBuilder();
            //订单的总价格
            double totalAmount = 0.0;
            //添加订单详情的个数
            int orderItemCount = 0;
            //循环列表添加订单详情
            for (ShoppingCart scart : cartlist) {
                //查询skuName
                QueryWrapper qw = new QueryWrapper();
                qw.eq("sku_id",scart.getSkuId());
                String skuName = skuMapper.selectOne(qw).getSkuName();
                //拼接untitled
                untitled.append(scart.getProductName()).append(",");
                //添加到总价格
                totalAmount += scart.getProductPrice()*Double.parseDouble(scart.getCartNum());
                //创建orderItem对象
                OrderItem orderItem = new OrderItem();
                    orderItem.setItemId(OrderItemIdUtil.getId().toString());
                    orderItem.setOrderId(orderId);
                    orderItem.setProductId(scart.getProductId());
                    orderItem.setProductName(scart.getProductName());
                    orderItem.setProductImg(scart.getProductImg());
                    orderItem.setSkuId(scart.getSkuId());
                    orderItem.setSkuName(skuName);
                    orderItem.setProductPrice(new BigDecimal(scart.getProductPrice()));
                    orderItem.setBuyCounts(Integer.parseInt(scart.getCartNum()));
                    orderItem.setTotalAmount(new BigDecimal(scart.getProductPrice()*Double.parseDouble(scart.getCartNum())));
                    orderItem.setBasketDate(scart.getCartTime());
                    orderItem.setBuyTime(currentTime);
                //添加操作
                int insert = orderItemMapper.insert(orderItem);
                if (insert > 0) orderItemCount++;
            }
            //添加订单
            if (orderItemCount > 0){
                Orders orders = new Orders();
                orders.setOrderId(orderId);
                orders.setUserId(userId);
                orders.setUntitled(untitled.toString());
                orders.setReceiverName(name);
                orders.setReceiverMobile(mobile);
                orders.setReceiverAddress(province + " " + city + " " + area + " " + addr);
                orders.setTotalAmount(new BigDecimal(totalAmount));
                orders.setActualAmount(new Double(totalAmount).intValue());
                orders.setStatus("1");
                orders.setCreateTime(currentTime);
                int insert = ordersMapper.insert(orders);
                if (insert > 0) return new ResultData(0,"订单添加成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData(310,"订单添加接口异常");
        }
        return new ResultData(311,"订单添加接口异常");
    }

    @Override
    public ResultData<Orders> selectByOrderId(String orderId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("order_id",orderId);
        Orders order = ordersMapper.selectOne(qw);
        if (order != null) return new ResultData(0,"查询成功",order);
        return new ResultData(312,"查询接口异常");
    }

    @Override
    public ResultData changeStatus(String orderId) {
        int i = ordersMapper.changeStatusByOrderId(orderId);
        if (i > 0) return new ResultData(0,"支付成功!");
        return new ResultData(314,"支付失败!");
    }

    @Override
    public ResultData faHuo(String orderId) {
        int i = ordersMapper.faHuo(orderId);
        if (i > 0) return new ResultData(0,"发货成功!");
        return new ResultData(316,"发货异常!");
    }

    @Override
    public ResultData shouHuo(String orderId) {
        int i = ordersMapper.shouHuo(orderId);
        if (i > 0) return new ResultData(0,"收货成功!");
        return new ResultData(320,"收货异常!");
    }

}
